import Vue from 'vue';
import Router, { Route } from 'vue-router';
import { PositionResult } from "vue-router/types/router";
import { UserModule } from '../store/modules/user';
import pageList from './pageList'
import authGuardList from './AuthGuard'
import guestGuardList from "./GuestGuard";
import { AppModule } from '../store/modules/app';

Vue.use(Router);

/**
 * @param  {Route} to
 * @param  {Route} from
 * @param  {Object|undefined} savedPosition
 * @return {Object}
 */
function scrollBehavior(to: Route, from: Route, savedPosition: any): PositionResult {
  if (savedPosition) {
    return savedPosition;
  }

  const position: any = {};

  if (to.hash) {
    position.selector = to.hash;
  }

  if (to.matched.some((m: any) => m.meta.scrollToTop)) {
    position.x = 0;
    position.y = 0;
  }

  return position;
};

/**
 * @param  {Array} routes
 * @param  {Function} guard
 * @return {Array}
 */
function guard(routes: any[], guard: any) {
  routes.forEach((route: any) => {
    route.beforeEnter = guard;
  });
  return routes;
}

/**
 * Add the "authenticated" guard.
 *
 * @param  {Array} routes
 * @return {Array}
 */
export function authGuard(routes: any, store: any) {
  return guard(routes, (to: any, from: any, next: any) => {
    if (store.authCheck) {
      next();
    } else {
      next('/Login');
    }
  });
};

function guestGuard(routes: any, store: any) {
  return guard(routes, (to: any, from: any, next: any) => {
    if (store.authCheck) {
      next('/');
    } else {
      next();
    }
  });
};


function jsonToMenu(jsonData: any) {
  for (let item in jsonData) {
    let subObj: any = (<any>jsonData)[item];
    let funct = pageList[subObj['componentName']];
    if (subObj['componentName']) {
      subObj['component'] = funct
    }
    if (subObj['children']) {
      subObj['children'] = jsonToMenu(subObj['children'])
    }
  }
  return jsonData;
}

function routeFromLocalStorage(name: string): any {
  // TODO 此功能后期转移到 store 部分
  let strJson: any = sessionStorage.getItem(name);
  let objJson: any = JSON.parse(strJson);
  return jsonToMenu(objJson);
}


export function routerData(store: any): any {
  let adminList: any = authGuard(routeFromLocalStorage('authMenu'), UserModule);
  let guardMenu: any = guestGuard(routeFromLocalStorage('menu'), UserModule);
  if (adminList[0]['children']) {
    let permissionList: Route[] = [...adminList[0].children]
    store.SYSTEM_MENU(permissionList)
  }
  return [
    ...adminList,
    ...guardMenu
  ];
}


export default () => {

  // if (!sessionStorage.getItem("menu")) {
  sessionStorage.setItem("menu", JSON.stringify(guestGuardList))
  // }
  //if (!sessionStorage.getItem("authMenu")) {
  sessionStorage.setItem("authMenu", JSON.stringify(authGuardList))
  //}
  const routes = routerData(AppModule);
  const router = new Router({
    mode: 'hash',
    base: process.env.BASE_URL,
    routes,
    scrollBehavior
  });

  router.beforeEach((to: Route, from: Route, next: any) => {
    const components = router.getMatchedComponents({ ...to });
    if (components.length) {
      setTimeout(() => {
        let bar: any = router.app.$root.$loadingBar
        if (bar) {
          bar.start();
        }
      }, 0);
      UserModule.reLogin().then(function () {
        next();
      })
    }

  });


  router.afterEach((to, from) => {
    setTimeout(() => {
      let bar: any = router.app.$root.$loadingBar
      if (bar) {
        bar.finish();
      }
    }, 0);
  });
  return router;
}
